/**
 * 基本信息
 *
 * @format
 */

import { BaseDao, TBAPIS } from '../../sdk'
import { ACTIVITY_CONFIG_DB_NAME, ENV_CONFIG_DB_NAME, KEY_DB_NAME, PUBLIC_SETTING_DB_NAME } from '../../db'
import { ACTIVITY_OPEN_PRIZE_STATUS, ACTIVITY_STATUS, BASE_CONFIG } from '../../constants'

export default class BaseService {
  context: IContext<any>
  activitydao: IBaseDao
  publicdao: IBaseDao
  envdao: IBaseDao
  keydao: IBaseDao
  constructor(context: IContext<any>) {
    this.context = context
    this.activitydao = new BaseDao(context, ACTIVITY_CONFIG_DB_NAME)
    this.publicdao = new BaseDao(context, PUBLIC_SETTING_DB_NAME)
    this.envdao = new BaseDao(context, ENV_CONFIG_DB_NAME)
    this.keydao = new BaseDao(context, KEY_DB_NAME)
  }
  /**
   * @desc 活动基本信息
   * @param {活动id} activityId
   * @returns 返回活动详情，若不存在活动，返回为null
   */
  async getBaseInfo(activityId: string): Promise<IActivityInfo> {
    return await this.activitydao.findOne({ _id: activityId, deleteStatus: ACTIVITY_STATUS.NORMAL })
  }

  /**
   * 活动列表
   */
  async getCurrentBaseInfoList(): Promise<string[]> {
    const now = Date.now()
    return await this.activitydao.find(
      {
        deleteStatus: ACTIVITY_STATUS.NORMAL,
        type: 'fireworks',
        startTime: { $lte: now },
        $or: [{ endTime: { $gte: now } }, { endTime: '' }]
      },
      { projection: { _id: 1 } }
    )
  }
  //获取公共参数
  async getCommonUrl(env:string) {
    const urlobj = {
      "10002":"https://m.duanqu.com/?_ariver_appid=3000000053747493&_mp_code=tb&transition=present",
      "10003":"https://m.duanqu.com?_ariver_appid=3000000048426063&nbsv=2.4.94&nbsource=debug&nbsn=TRIAL&_mp_code=tb&transition=present",
      "10014":"https://m.duanqu.com/?_ariver_appid=3000000053749622&_mp_code=tb&transition=present"
    }
    try {
        //查询数据库商家的session信息
        const result = await this.keydao.findOne({
            name: 'url',
            type: 'common',
            env
        });
        if(result) {
          return{
            url:result,
            openId:this.context.openId,
            currentTime: Date.now()
          }
        }
        return {
            url:urlobj,
            openId:this.context.openId,
            currentTime: Date.now()
          }
    } catch (error) {
        return false
    }
  }

  /**
   * 公共配置
   * @param isNike 
   */
  async getExtraInfo(isNike: boolean): Promise<IActivityInfo> {
    return await this.publicdao.findOne({ type: 'pile', isNike })
  }

  /**
   *
   * 根据itemIds获取商品列表
   *
   * @param {string} itemIds
   * @param {string} session
   * @return {Array}
   * @memberof BaseService
   */
  async getItemListByIds(itemIds: string, session: string): Promise<{ list: ITaoBaoItems[] }> {
    const GOODSINFO =
      'detail_url,approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,desc,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id,sold_quantity'
    const result = await TBAPIS.getItemListByItemIds(this.context, itemIds, { fields: GOODSINFO }, session)
    const items = result?.items?.item || []
    const list = items.map(
      (v: { num_iid: string; title: string; price: string; detail_url: string; pic_url: string; desc: string }) => {
        return {
          itemId: v.num_iid,
          name: v.title,
          price: v.price,
          url: v.detail_url,
          image: v.pic_url,
          desc: v.desc
        }
      }
    )
    return { list }
  }

  /**
   * 获取需要开奖的活动列表
   */
  async getNeedRewardsActivityList() {
    return await this.activitydao.find<IActivityInfo>({
      endTime: { $lt: Date.now() },
      openPrizeStatus: { $in: [ACTIVITY_OPEN_PRIZE_STATUS.AWAIT, ACTIVITY_OPEN_PRIZE_STATUS.FAIL] }
    })
  }

  /**
   * 获取相关配置信息
   */
  async getEnvConfig() {
    const env = this.context.env
    const { envType } = this.context.data
    if (envType) {
      const envConfig = await this.envdao.findOne({ envType })
      if (envConfig) {
        //如果存在config信息，则返回相关信息
        return envConfig
      } else if (env) {
        return await this.envdao.findOne({ envType: env })
      } else {
        return BASE_CONFIG
      }
    } else {
      return (await this.envdao.findOne({ envType: env })) || BASE_CONFIG
    }
  }
  
}
